package com.hsd.netty.client.task;

import com.google.gson.Gson;
import com.hsd.netty.client.common.NettyHeader;
import com.hsd.netty.client.common.NettyMessage;
import com.hsd.netty.client.enums.MessageType;
import com.hsd.netty.client.cache.OverallStaticCache;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author s.he
 * on 2020/6/6
 */
public class HeartBeatTask implements Runnable {
    private static final Logger logger = LoggerFactory.getLogger(HeartBeatTask.class);

    private ChannelHandlerContext ctx;

    public HeartBeatTask(ChannelHandlerContext ctx) {
        this.ctx = ctx;
    }

    @Override
    public void run() {
        boolean active = ctx.channel().isActive();
        if(!active) {
            logger.info("连接已经断开了, 将停止和服务器端的心跳");
            ctx.executor().shutdownGracefully();
            return;
        }
        NettyMessage nettyMessage = new NettyMessage();
        NettyHeader nettyHeader = new NettyHeader();
        nettyHeader.setType(MessageType.HEART_BEAT.getCode());
        Long sessionId = OverallStaticCache.getSessionId();
        OverallStaticCache.loginInfoMap.put("isHeartBeat", "true");
        if(sessionId != 0) {
            nettyHeader.setSessionId(sessionId);

        }
        nettyMessage.setNettyHeader(nettyHeader);
        Gson gson = new Gson();
        logger.info("【心跳请求】客户端发送心跳信息, 心跳报文为:" + gson.toJson(nettyMessage));
        ctx.writeAndFlush(nettyMessage);
    }
}
